package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.AddPictureAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.AchievementEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.PictureListEntity;
import com.runen.infinitemovement.model.entity.PublishEntity;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.ScreenShotHelper;
import com.runen.infinitemovement.tool.UiUtil;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.JsonUtils;
import com.runen.rxnetlibrary.utils.LogUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.zhihu.matisse.Matisse;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PublishStatusActivity extends BaseActivity {

    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.top_btn_right)
    Button topBtnRight;
    @BindView(R.id.top_iv_right)
    ImageView topIvRight;
    @BindView(R.id.rv_add_picture)
    RecyclerView rvAddPicture;
    @BindView(R.id.iv_map)
    ImageView ivMap;
    @BindView(R.id.tv_challenge_name)
    TextView tvChallengeName;
    @BindView(R.id.edt_input_star)
    EditText edtInputStar;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.ll_picture)
    LinearLayout llPicture;
    @BindView(R.id.tv_activity_num)
    TextView tvActivityNum;
    @BindView(R.id.ll_activity_go)
    LinearLayout llActivityGo;
    @BindView(R.id.ll_achievement)
    LinearLayout llAchievement;
    @BindView(R.id.rci_bg)
    RoundedCornersImage rciBg;
    @BindView(R.id.tv_start_end_name)
    TextView tvStartEndName;
    @BindView(R.id.tv_rank)
    TextView tvRank;
    @BindView(R.id.tv_prize)
    TextView tvPrize;
    @BindView(R.id.iv_medalUrl)
    ImageView ivMedalUrl;
    private AddPictureAdapter addPictureAdapter;
    private List<String> stringList = new ArrayList<>();
    private String bucketName;
    private int REQUEST_CODE_CHOOSE = 23;
    private List<Uri> avatar;
    private int publishFlag = 0;
    private PublishEntity publishEntity;
    private String imgUrl;
    private String motionId;
    private AchievementEntity.DataBean dataBean;

    /**
     * 图片名字
     */

    @Override
    protected int getLayoutId() {
        return R.layout.activity_publish_status;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        publishFlag = getIntent().getIntExtra("PUBLISH_FLAG", 0);
        publishEntity = new PublishEntity();
        if (publishFlag == 0) {
            llActivityGo.setVisibility(View.VISIBLE);
            llPicture.setVisibility(View.GONE);
        } else if (publishFlag == 1) {
            llActivityGo.setVisibility(View.GONE);
            imgUrl = getIntent().getStringExtra("imgUrl");
            motionId = getIntent().getStringExtra("motionId");
            dataBean = JsonUtils.fromJson(getIntent().getStringExtra("AchievementData"), AchievementEntity.DataBean.class);
            if (!TextUtils.isEmpty(imgUrl)) {
                llAchievement.setVisibility(View.GONE);
                llPicture.setVisibility(View.VISIBLE);
                publishEntity.motionImage = imgUrl;
                publishEntity.motionId = motionId;
                ivMap.setVisibility(View.VISIBLE);
                GlideUtils.loadImage(PublishStatusActivity.this, imgUrl, ivMap);
            } else if (null != dataBean) {
                ivMap.setVisibility(View.GONE);
                llAchievement.setVisibility(View.VISIBLE);
                llPicture.setVisibility(View.VISIBLE);
                publishEntity.achievement = dataBean.id;
                GlideUtils.loadImage(this, dataBean.cover, rciBg);
                tvStartEndName.setText(dataBean.startPoint + "-" + dataBean.endPoint);
                tvRank.setText(String.valueOf(dataBean.rank));
                tvPrize.setText(dataBean.prize);
                GlideUtils.loadImage(this, dataBean.medalUrl, ivMedalUrl);
            }

        } else {
            llActivityGo.setVisibility(View.GONE);
            llPicture.setVisibility(View.GONE);
        }
        topTitle.setText("发布动态");
        topBtnRight.setText("发布");

        LinearLayoutManager layoutManager = new GridLayoutManager(this, 3);
        rvAddPicture.setLayoutManager(layoutManager);
        addPictureAdapter = new AddPictureAdapter(this);
        rvAddPicture.setAdapter(addPictureAdapter);
        onAddPicture(null);
        addPictureAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (addPictureAdapter.getData().get(position).equals("nullUrl")) {
                    requestCamera();
                }
            }
        });
        addPictureAdapter.setOnDeleteClick(new AddPictureAdapter.OnDeleteClick() {
            @Override
            public void onDelete(String item) {
                for (int i = 0; i < stringList.size(); i++) {
                    if (stringList.get(i).equals(item)) {
                        stringList.remove(i);
                    }
                }
                if (!stringList.get(stringList.size() - 1).equals("nullUrl")) {
                    stringList.add(stringList.size(), "nullUrl");
                }
                addPictureAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 获取拍照权限
     */
    private void requestCamera() {
        UiUtil.getImageSelectorConfig9(this, REQUEST_CODE_CHOOSE);
    }

    String activity_ids = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) {
            if (null != data) {
                int activity_num = data.getIntExtra("activity_num", 0);
                activity_ids = data.getStringExtra("activity_id");
                String string = "%s 个关联活动";
                tvActivityNum.setText(String.format(string, activity_num));
            }
        }
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                avatar = Matisse.obtainResult(data);
                onAddPicture(avatar);
            }

            Log.e("OnActivityResult ", String.valueOf(Matisse.obtainOriginalState(data)));
        }

    }

    private void onAddPicture(List<Uri> datas) {

        if (stringList.size() > 0) {
            stringList.remove(stringList.size() - 1);
        }
        if (datas != null && datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                String clipUrl = datas.get(i).toString();
                if (stringList.size() < 9) {
                    stringList.add(clipUrl);
                }
            }
        }
        if (stringList.size() < 9) {
            stringList.add(stringList.size(), "nullUrl");
        }
        addPictureAdapter.setNewInstance(stringList);
        addPictureAdapter.notifyDataSetChanged();
    }

    private void updateByImgUrl() {
        if (TextUtils.isEmpty(edtInputStar.getText().toString().trim())) {
            ToastUtils.showShort("动态描述不能为空");
            return;
        }
        showDialog("上传图片中...", false);
        if (publishFlag == 0) {
            publishEntity.motionRecord = false;
        } else {
            publishEntity.motionRecord = true;
        }
        publishEntity.content = edtInputStar.getText().toString().trim();
        publishEntity.activities = new ArrayList<>();
        if (!TextUtils.isEmpty(activity_ids)) {
            String[] result = activity_ids.split(",");
            for (String r : result) {
                publishEntity.activities.add(r);
            }
        }
        publishEntity.images = new ArrayList<>();
        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < stringList.size(); i++) {
            if (!stringList.get(i).equals("nullUrl")) {
//                File file = ScreenShotHelper.compressImage2(CommonUtil.getImage(stringList.get(i)), this);
                File file = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                    file = CommonUtil.uriToFileApiQ(this, Uri.parse(stringList.get(i)));
                } else {
                    file = CommonUtil.uri2File(this, Uri.parse(stringList.get(i)));
                }
                fileList.add(file);
            }
        }
        if (fileList.size() > 0) {
            TreeMap<String, String> mapType = new TreeMap<>();
            mapType.put("type", "trendsImg");
            TreeMap<String, List<File>> map = new TreeMap<>();
            map.put("files", fileList);
            new UserAPI().putFiles(mapType, map, new BaseResultCallback<PictureListEntity>() {
                @Override
                public void onResponse(PictureListEntity response) {
                    if (null != response) {
                        if (response.code == 0) {
                            if (response.data != null && response.data.size() > 0) {
                                for (int i = 0; i < response.data.size(); i++) {
                                    publishEntity.images.add(response.data.get(i).url);
                                }
                                onSend();
                            }
                        }
                    }
                }
            });
        } else {
            onSend();
        }

    }

    @OnClick({R.id.top_btn_left, R.id.top_btn_right, R.id.ll_activity_go})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.top_btn_right:
                onPublish();
                break;
            case R.id.ll_activity_go:
                Intent intent = new Intent(this, AssociatedActivitiesActivity.class);
                startActivityForResult(intent, 100);
                break;
        }
    }

    /**
     * 发布
     */
    private void onPublish() {
        updateByImgUrl();
    }

    private void onSend() {
        new ActivityAPI().publishDynamics(JsonUtils.toJson(publishEntity), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                dismissDialog();
                if (response.getCode() == 0) {
                    EventBus.getDefault().post(new EventBusEntity(8));
                    ToastUtils.showShort(response.getMessage());
                    finish();
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();
                dismissDialog();
            }
        });
    }
}
